from django.urls import path
from django.http import HttpResponseRedirect
from django.contrib import admin, messages
from .connectors import connect_pile, disconnect_pile
from .views import manage_gun_status, update_gun_status

app_name = 'iot'  # 重要：设置应用命名空间

def connect_pile_view(request, pile_id):
    """连接充电桩视图"""
    try:
        if connect_pile(pile_id):
            messages.success(request, "连接成功")
        else:
            messages.error(request, "连接失败")
    except Exception as e:
        messages.error(request, f"连接错误: {str(e)}")
    return HttpResponseRedirect("/admin/iot_ykc_simulator/pile/")

def disconnect_pile_view(request, pile_id):
    """断开充电桩视图"""
    try:
        if disconnect_pile(pile_id):
            messages.success(request, "断开成功")
        else:
            messages.error(request, "断开失败")
    except Exception as e:
        messages.error(request, f"断开错误: {str(e)}")
    return HttpResponseRedirect("/admin/iot_ykc_simulator/pile/")

urlpatterns = [
    path('pile/<int:pile_id>/manage_gun_status/', manage_gun_status, name='manage_gun_status'),
    path('pile/<int:pile_id>/update_gun_status/', update_gun_status, name='update_gun_status'),
    path('pile/<int:pile_id>/connect/', connect_pile_view, name='connect_pile'),
    path('pile/<int:pile_id>/disconnect/', disconnect_pile_view, name='disconnect_pile'),
]